package ytdp.careagle.com.ytdp.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.widget.TextView;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.analytics.dplus.UMADplus;

import junit.framework.Test;

import java.io.File;
import java.util.HashMap;

import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import ytdp.careagle.com.ytdp.R;
import ytdp.careagle.com.ytdp.app.G;
import ytdp.careagle.com.ytdp.app.Operation;
import ytdp.careagle.com.ytdp.callback.MyDialogCallback2;
import ytdp.careagle.com.ytdp.entity.BaseConfig;
import ytdp.careagle.com.ytdp.entity.VersionControlEntity;
import ytdp.careagle.com.ytdp.mvp.mode.CarEvaluateModel;
import ytdp.careagle.com.ytdp.net.MyObserver;
import ytdp.careagle.com.ytdp.net.NetWorks;
import ytdp.careagle.com.ytdp.net.Result;
import ytdp.careagle.com.ytdp.utils.RxPromisUtils;
import ytdp.careagle.com.ytdp.utils.SPUtils;

public class WelcomeActivity extends BaseActivity {

    private static final int GOTO_NEXT = 1002;

    private static final long SPLASH_DELAY_MILLIS = 2000;
    private boolean isGetBaseCfg = false;
    private boolean isTimeGone = false;
    private boolean isLastVersion = true;
    private String token;


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)

    @Override
    public int getLayoutId() {
        return R.layout.activity_welcome;
    }

    @Override
    public void initView() {
        token = (String) SPUtils.get(getApplicationContext(), "token", "");
        UMADplus.track(this, "闪屏页", null);
        if (!this.isTaskRoot()) { //判断该Activity是不是任务空间的源Activity，“非”也就是说是被系统重新实例化出来
            //如果你就放在launcher Activity中话，这里可以直接return了
            Intent mainIntent = getIntent();
            String action = mainIntent.getAction();
            if (mainIntent.hasCategory(Intent.CATEGORY_LAUNCHER) && action.equals(Intent.ACTION_MAIN)) {
                finish();
                return;//finish()之后该活动会继续执行后面的代码，你可以logCat验证，加return避免可能的exception
            }
        }
        getNetVersion();
        init();
        TextView tvVersion = (TextView) findViewById(R.id.tv_version);
        tvVersion.setText("Version " + G.APPVERSION);
    }

    private void init() {
        if (!TextUtils.isEmpty(token)) {
            new CarEvaluateModel().getBasicConfig(this, G.getHeader(this), new MyObserver<Result<BaseConfig>>() {
                @Override
                public void onNext(Result<BaseConfig> baseConfigResult) {
                    super.onNext(baseConfigResult);
                    if (baseConfigResult.getCode() == G.REQUEST_OK) {
                        BaseConfig.DefaultCityBean defaultCity = baseConfigResult.getData().getDefault_city();
                        String extension = defaultCity.getExtension();
                        String value = defaultCity.getValue();
                        if (extension != null) {
                            SPUtils.put(WelcomeActivity.this, "city_extension", extension);
                            SPUtils.put(WelcomeActivity.this, "city_value", value);
                        }
                        String faceExtension = baseConfigResult.getData().getIdentify_remind().getExtension();
                        SPUtils.put(WelcomeActivity.this, "faceExtension", faceExtension);
                    }
                    isGetBaseCfg = true;
                    if (isTimeGone) {
                        initApp();
                    }
                }

                @Override
                public void onError(Throwable e) {
                    super.onError(e);
                    isGetBaseCfg = true;
                    if (isTimeGone) {
                        initApp();
                    }
                }
            });
        } else {
            isGetBaseCfg = true;
        }
        this.mHandler.sendEmptyMessageDelayed(GOTO_NEXT, SPLASH_DELAY_MILLIS);
        //在SD卡下建目录
        String dir = G.getFileRootPath();
        File f = new File(dir);
        if (!f.exists()) {
            f.mkdir();
        }
        //获取屏幕尺寸
        getScreenSize();
//        ImageLoadManager.getImageLoadManager().downLoadPic(this, null, null);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GOTO_NEXT:
                    if (isGetBaseCfg && isLastVersion) {
                        isTimeGone = true;
                        initApp();
                    }
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private void initApp() {
        if (TextUtils.isEmpty(token)) {
            getOperation().forward(LoginActivity.class);
        } else {
            Operation operation = getOperation();
            operation.forward(CarEvaluateQueryActivity.class);
        }
        finish();
//        new RxPermissions(WelcomeActivity.this)
//                .request(Manifest.permission.CAMERA,
//                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                .subscribe(new Consumer<Boolean>() {
//                    @Override
//                    public void accept(@NonNull Boolean aBoolean) {
//                        try {
//                            Camera camera = Camera.open(G.CAMERA_FRONT_OR_BACK);
//                            camera.release();
//                            camera = null;
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                            showMessage("请到设置中同意相关权限");
//                            return;
//                        }
//                        if (aBoolean) {
//
//                        } else {
//                            showMessage("请到设置中同意相关权限");
//                        }
//                    }
//                });
    }


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

    }

    public void getScreenSize() {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int W = dm.widthPixels;
        int H = dm.heightPixels;
        SPUtils.put(this, "" +
                "screenWidth", "" + W);
        SPUtils.put(this, "screenHeight", "" + H);
    }

    public void getNetVersion() {
        HashMap<String, String> map = new HashMap<>();
        map.put("platform", "ANDROID");
        NetWorks.getInstance().getCurrVersion(this, map, new MyObserver<Result<VersionControlEntity>>() {
            @Override
            public void onNext(final Result<VersionControlEntity> versionControlEntityResult) {
                super.onNext(versionControlEntityResult);
                if (versionControlEntityResult.getCode() == G.REQUEST_OK) {
                    if (!VersionControlEntity.isNewVersion(versionControlEntityResult.getData().getLastAppVersion(), G.APPVERSION)) {
                        isLastVersion = false;
                        showLoadLastDialog(versionControlEntityResult.getData());
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }

        });
    }

    private void showLoadLastDialog(final VersionControlEntity versionControlEntityResult) {
        showMyDialog2("有最新版本请立即更新?", versionControlEntityResult.getDescription().toString(), new MyDialogCallback2() {
            @Override
            public void onClickOk(DialogInterface dialogInterface, int which) {
                Uri uri = Uri.parse(versionControlEntityResult.getDownloadLink());
                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(it);
                finish();
            }

            @Override
            public void onCancel(DialogInterface dialogInterface, int which) {
                //小于最小版本
                finish();
            }
        });
    }
}
